package org.dna.wicketui.users;

import java.util.Arrays;
import java.util.List;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.dna.MetroApplication;
import org.dna.metronomo.persistence.IUserDAO;
import org.dna.metronomo.persistence.User;
import org.dna.uimodel.LoadableUserModel;
import org.dna.uimodel.SelectableUser;

/**
 * This panel contains a form to add or modify a single user.
 */
public class UserDetailsPanel extends Panel {

    private static final long serialVersionUID = 7319439810311901658L;
    private boolean m_editMode = false;
    private Button btnSumbit;
    private TextField<String> tfName;
    private PasswordTextField tfPassword;
    private IModel<User> m_userModel;

    public UserDetailsPanel(String id) {
        super(id);
        m_editMode = false;
        m_userModel = new Model<User>(new User());
        initComponents();
    }

    public UserDetailsPanel(String id, SelectableUser user) {
        super(id);
        m_editMode = true;
        if (user != null) {
            m_userModel = new LoadableUserModel(user);
        }
        initComponents();
    }

    @SuppressWarnings({"serial", "unchecked"})
    private void initComponents() {
        Form form = new Form("form") {

            @Override
            protected void onSubmit() {
                IUserDAO dao = MetroApplication.get().getUserDAO();
                User user = (User) getModelObject();
                if (m_editMode) {
                    dao.update(user);
                } else {
                    dao.addNewUser(user);
                }
            }
        };
        form.setModel(new CompoundPropertyModel(m_userModel));
        add(form);
        tfName = new TextField("name");
        tfPassword = new PasswordTextField("password");
        String submitLabel = "Update";
        if (!m_editMode) {
            submitLabel = "Create";
            tfName.setRequired(true);
        } else {
            tfName.setEnabled(false);
        }
        btnSumbit = new Button("button", new Model(submitLabel));
        form.add(btnSumbit);
        form.add(tfName);
        form.add(tfPassword);

        //Roles list
        List<String> roles = Arrays.asList("Admin", "User");
        form.add(new ListChoice("role", new PropertyModel(m_userModel, "role"),
                roles));
//		user.setRole("User"); //this change the role of the user current logged in, so an admin became User only because navigate this page
    }
}
